package com.kcht.itsed.mws.aleframework.biz;

import com.kcht.itsed.mws.aleframework.intf.ILogicalReaderContainer;
import com.kcht.itsed.mws.alemodel.LRSpec;
import com.kcht.itsed.mws.commmodel.SpecId;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
public class LogicalReaderContainer implements ILogicalReaderContainer{

	private Map<String,LRSpec> lrSpecContainer = new HashMap<>();
	private Map<String,Set<SpecId>> lrRelatedSpecContainer = new HashMap<>();
	
	@Override
	public synchronized void updateLRSpec(String lrSpecName, LRSpec lrSpec) {
		lrSpecContainer.put(lrSpecName, lrSpec);
		if(!lrRelatedSpecContainer.containsKey(lrSpecName))lrRelatedSpecContainer.put(lrSpecName, new HashSet<SpecId>());
	}

	@Override
	public synchronized void removeLRSpec(String lrSpecName) {
		lrSpecContainer.remove(lrSpecName);
		lrRelatedSpecContainer.remove(lrSpecName);
	}
	
	@Override
	public synchronized boolean isLrReferencesByActiveSpec(String lrSpecName) {
		return lrRelatedSpecContainer.containsKey(lrSpecName) && lrRelatedSpecContainer.get(lrSpecName).size()!=0;
	}
	
	
	@Override
	public synchronized void bindActiveEcSpecToLr(String ecSpecName, String lrName) {
		lrRelatedSpecContainer.get(lrName).add(new SpecId(SpecId.EC,ecSpecName));
	}
	
	@Override
	public synchronized void bindActiveCcSpecToLr(String ccSpecName, String lrName) {
		lrRelatedSpecContainer.get(lrName).add(new SpecId(SpecId.CC,ccSpecName));
	}
	
	@Override
	public synchronized void removeLrEcRelation(String ecSpecName) {
		SpecId sid = new SpecId(SpecId.EC,ecSpecName);
		lrSpecContainer.keySet().forEach(lrName->lrRelatedSpecContainer.get(lrName).remove(sid));
	}

	@Override
	public synchronized void removeLrCcRelation(String ccSpecName) {
		SpecId sid = new SpecId(SpecId.CC,ccSpecName);
		lrSpecContainer.keySet().forEach(lrName->lrRelatedSpecContainer.get(lrName).remove(sid));
	}
	
	@Override
	public synchronized LRSpec getLRSpec(String lrSpecName) {
		return lrSpecContainer.get(lrSpecName);
	}
}
